package com.lysj.bhp.wallet.service;

import com.lysj.bhp.wallet.base.WalletContent;
import com.lysj.bhp.wallet.domain.EthereumWallet;
import com.lysj.bhp.system.base.BaseConst;
import org.springframework.stereotype.Service;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.WalletUtils;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.response.EthGetBalance;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.tx.Transfer;
import org.web3j.utils.Convert;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Map;
import java.util.concurrent.ExecutionException;

@Service
public class EthereumService extends WalletContent {

    /**
     * 查询账户余额
     */
    @Deprecated
    public BigInteger getBalance() {
        try {
            EthGetBalance balance = web3
                    .ethGetBalance("0xddbd2b932c763ba5b1b7ae3b362eac3e8d40121", DefaultBlockParameterName.LATEST)
                    .sendAsync()
                    .get();
            return balance.getBalance();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 创建一个以太坊交易
     */
    public Map<String, String> transaction(EthereumWallet ethereumWallet, String toAddress, Long amount) {

        try {
            Credentials credentials = WalletUtils.loadCredentials(ethereumWallet.getPassword(), BaseConst.KEY_STORE_DIR + ethereumWallet.getKeystore());
            TransactionReceipt transactionReceipt = Transfer.sendFunds(
                    web3, credentials, toAddress,
                    BigDecimal.valueOf(amount), Convert.Unit.ETHER).send();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
